<template>
  <view class="body">
    <view class="progress">
      <up-line-progress
        :percentage="100 * (current / state.total) || 0"
        activeColor="#A46B39"
        inactiveColor="#f5f5f5"
        :showText="false"
        height="16"
      />
      <text class="nums"
        ><text style="font-size: 28rpx; color: #a46b39">{{ current }}</text
        >/{{ state.total }}</text
      >
    </view>
    <scroll-view
      class="scroll-X"
      scroll-x="true"
      :scroll-with-animation="true"
      :scroll-into-view="tabId"
    >
      <view class="tabList">
        <view
          :id="'scroll_' + index"
          :class="['item', state.tabActive == index ? 'on' : '']"
          v-for="(item, index) in state.tabList"
          :key="index"
          @tap="tabFun(index)"
        >
          <text class="text">{{ item }}</text>
        </view>
      </view>
    </scroll-view>
    <view class="wrap">
      <scroll-view
        v-if="state.questionList.length > 0"
        :scroll-top="scrollTop"
        @scroll="scroll"
        class="scroll-Y"
        scroll-y="true"
      >
        <view
          v-for="(item, index) of state.questionList[Number(state.tabActive)]?.list"
          :key="index"
          class="list_item"
        >
          <!-- <view v-if="index == 0" class="form_name">{{ item.questionName }}</view> -->
          <view v-if="index == 0" class="tips">请根据近一年的体验和感觉，回答以下问题</view>
          <view class="list_item_title">
            <view class="nums"
              ><text style="color: #a46b39">{{ index + 1 }}</text
              >/{{ state.questionList[state.tabActive].list?.length }}</view
            >
            <view class="title">{{ item.questionName }}</view>
          </view>
          <view
            v-if="item.questionType == '单选' || item.questionType == '单选+输入'"
            class="selects"
          >
            <view class="question">
              <view class="answer">
                <view
                  v-for="(i, idx) of item.options"
                  :key="idx"
                  @click="select(i, item)"
                  :class="['answer_item', i.check ? 'on' : '']"
                >
                  {{ i.value }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="fixed">
      <button v-if="state.tabActive != 0" class="pre_btn" @tap="prev()">上一步</button>
      <button v-if="state.tabActive != state.tabList.length - 1" class="next_btn" @tap="next()">
        下一步
      </button>
      <button v-if="state.tabActive == state.tabList.length - 1" class="next_btn" @tap="next()">
        提交问卷
      </button>
    </view>
    <up-modal
      :show="modalShow"
      :title="'中医指导'"
      :closeOnClickOverlay="true"
      :confirmColor="'#A46B39'"
      confirmText="知道了"
      @confirm="confirm"
      @close="modalShow = false"
    >
      <view
        style="width: 100%; font-size: 30rpx; font-weight: 400; color: #4e5969; text-align: center"
        >问卷提交成功!</view
      >
    </up-modal>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, nextTick } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { debounce, throttle, deepCopy, getDate } from '@/utils/tools'
import { new_question, weight_save } from '../../api/sleep'
import { formatDate } from '@/utils/util'
import store from '@/store'

const state = reactive({
  tabActive: 0,
  total: 0,
  tabList: [],
  questionList: [],
  questionInfo: {}
})
const tabId = ref('')

const userInfo = ref({})
const modalShow = ref(false)

const scrollTop = ref(0)
const oldScrollTop = ref(0)

let currentId = ''

const current = computed(() => {
  let num = 0
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      if (val.value != '' || val.value.length > 0 || (val.inputText && val.inputText != '')) {
        num++
      }
    })
  })
  return num
})

watch(
  () => state.tabActive,
  () => {
    scrollTop.value = oldScrollTop.value
    nextTick(() => {
      scrollTop.value = 0
    })
  }
)

onShow(() => {
  userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  if (!currentId || currentId !== userInfo.value.patientInfo.empi) {
    currentId = deepCopy(userInfo.value.patientInfo.empi)
    // currentId = '74567895'
    init()
  }
})

onLoad(() => {
  wx.enableAlertBeforeUnload({
    message: '确认要退出吗？您填写的内容未提交',
    success: function (res) {
      console.log('成功', res)
    },
    fail: function (errMsg) {
      console.log('失败', errMsg)
    }
  })
})

const init = async () => {
  const params = { clientId: 10, empi: currentId }
  await new_question(params).then((res) => {
    state.questionList = JSON.parse(res.data.content)
    state.questionInfo = res.data
  })
  state.questionList.forEach((item) => {
    state.tabList.push(item.name)
    state.total += item.list.length
  })
  console.log('问卷内容', state.questionList)
}
const tabFun = (index: number) => {
  // tab切换
  if (state.tabActive !== index) {
    state.tabActive = index
    tabId.value = 'scroll_' + index
  }
}

const select = (item: any, val: any) => {
  if (item.disabled) {
    return
  }
  if (val.questionType == '单选') {
    // 单选逻辑
    val.options.forEach((i) => {
      i.check = false
    })
    val.value = item.value
    val.option = item.id
    val.scores = item.score
  } else {
    // 多选选逻辑
    if (!val.value) {
      val.value = item.value
      val.option = item.id
      val.scores = item.score
    } else {
      if (!item.check) {
        val.value = val.value + ',' + item.value
        val.option = val.option + ',' + item.id
        val.scores += item.score
      } else {
        val.value = val.value.replace(item.value + ',', '')
        val.value = val.value.replace(',' + item.value, '')
        val.value = val.value.replace(item.value, '')
        val.option = val.option.replace(item.id + ',', '')
        val.option = val.option.replace(',' + item.id, '')
        val.option = val.option.replace(item.id, '')
        val.scores -= item.score
      }
    }
  }
  item.check = !item.check
}

const prev = () => {
  state.tabActive--
  tabId.value = 'scroll_' + state.tabActive
}
const next = () => {
  let canNext = true
  state.questionList[state.tabActive].list.forEach((item) => {
    // 非输入类判断value是否为空，为输入时判断inputText是否为空
    if (
      (item.questionType != '输入' && (!item.value || item.value.length == 0)) ||
      (item.questionType == '输入' && !item.inputText)
    ) {
      canNext = false
    }
  })
  if (canNext) {
    // 通过必填校验，为最后一题则提交否则跳转下一题
    if (state.tabActive == state.questionList.length - 1) {
      confirm()
    } else {
      state.tabActive++
      tabId.value = 'scroll_' + state.tabActive
    }
  } else {
    uni.showToast({
      title: '请完成' + state.tabList[state.tabActive] + '题目填写',
      icon: 'none'
    })
  }
}

const confirm = () => {
  if (current.value != Number(state.total)) {
    uni.showToast({
      title: '请完成所有题目填写',
      icon: 'none'
    })
    return
  }
  const params = {
    clientId: 10,
    patientQuestionnaireAnswerVOs: []
  }
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      const answer = {
        id: state.questionInfo.id,
        userId: userInfo.value.userId,
        empi: currentId,
        creator: '',
        createTime: state.questionInfo.createTime,
        updateTime: getDate('YY-MM-DD hh:mm:ss'),
        questionnaireId: state.questionInfo.questionnaireId,
        questionId: val.id,
        questionnaireRecordId: '',
        optionId: val.questionType == '单选' || val.questionType == '多选' ? val.option : '',
        content: val.questionType == '输入' ? val.inputText : val.value,
        extContent: val.questionType == '选择 + 输入' ? val.inputText : '',
        score: val.scores
      }
      params.patientQuestionnaireAnswerVOs.push(answer)
    })
  })
  uni.showLoading({
    title: '正在提交中...',
    mask: true
  })
  weight_save(params).then((res) => {
    if (res.code == 0) {
      userInfo.value.patientInfo.questionState = true
      store.commit('SET_USERINFO', userInfo.value)
      uni.hideLoading()
      uni.showToast({
        title: '问卷提交成功！',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.redirectTo({
              url: '/module/src/pages/traditionalCMG/recordDetail?id=' + res.data
            })
          }, 2000)
        }
      })
    }
  })
}

const scroll = (e: any) => {
  oldScrollTop.value = e.target.scrollTop
}
</script>

<style lang="scss" scoped>
.body {
  height: 100vh;
  background: #fafafa;

  .progress {
    display: flex;
    gap: 16rpx;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 32rpx;
    background: #fff;

    .nums {
      font-size: 24rpx;
      font-weight: 400;
      color: #c9cdd4;
    }
  }

  .scroll-X {
    width: calc(100% - 64rpx);
    padding: 0 32rpx 24rpx;
    overflow-x: scroll;
    background: #fff;

    .tabList {
      white-space: nowrap;

      .item {
        position: relative;
        display: inline-block;
        height: 64rpx;
        padding: 0 30rpx;
        margin-right: 24rpx;
        font-size: 28rpx;
        line-height: 64rpx;
        color: #222;
        text-align: center;
        vertical-align: middle;
        background: #fafafa;
        border-radius: 32rpx;

        &:nth-last-child(1) {
          margin-right: 0;
        }

        &.on {
          font-weight: 700;
          color: #fff;
          background: #a46b39;
        }
      }
    }
  }

  .wrap {
    height: calc(100vh - 380rpx);
    padding: 32rpx;
    padding-top: 0;
    background: #fafafa;
    // overflow-y: scroll;

    .scroll-Y {
      position: relative;
      height: calc(100vh - 380rpx);
      overflow-y: scroll;
    }

    .list_title {
      margin: 26rpx 28rpx 22rpx;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
    }

    .img_bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 686rpx;
      height: 208rpx;
    }

    .list_item {
      padding: 32rpx;
      margin-top: 24rpx;
      background: #fff;
      border-radius: 16rpx;

      .form_name {
        font-size: 36rpx;
        font-weight: 700;
        color: #222;
      }

      .tips {
        margin-top: 8rpx;
        margin-bottom: 32rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: #999;
      }

      .list_item_title {
        display: flex;
        gap: 8rpx;
        align-items: top;
        justify-content: flex-start;

        .nums {
          padding-top: 4rpx;
          font-size: 24rpx;
          font-weight: 700;
          color: #666;
        }

        .tag {
          width: 80rpx;
          height: 40rpx;
          font-size: 24rpx;
          font-weight: 500;
          line-height: 40rpx;
          color: #fff;
          text-align: center;
          background: #02bcc3;
          border-radius: 4rpx;
        }

        .check {
          background: #5c8eff;
        }

        .title {
          width: 550rpx;
          font-size: 32rpx;
          font-weight: 700;
          color: #222;
        }
      }

      .selects {
        .question {
          margin-bottom: 40rpx;

          :last-child {
            margin: 0;
          }

          .answer {
            display: flex;
            flex-wrap: wrap;
            gap: 16rpx;
            justify-content: space-between;
            margin-top: 32rpx;

            .answer_item {
              box-sizing: border-box;
              width: 48%;
              padding: 16rpx 24rpx;
              font-size: 28rpx;
              font-weight: 400;
              color: #222;
              text-align: center;
              background: #fafafa;
              border: 1rpx solid #fafafa;
              border-radius: 8rpx;
              transform: rotateZ(360deg);

              &.on {
                font-size: 28rpx;
                font-weight: 500;
                color: #a46b39;
                background: rgb(164 107 57 / 10%);
                border: 1rpx solid #a46b39;
                border-radius: 8rpx;
              }

              &.disabled {
                color: #999;
                background: #f5f5f5;
              }
            }

            .w100 {
              width: 100%;
            }
          }
        }
      }

      .input {
        padding: 16rpx 24rpx;
        margin-top: 8rpx;
        margin-left: 64rpx;
        border: 1rpx solid #e5e6eb;
        border-radius: 4rpx;
      }

      .input_type {
        width: 560rpx;
        margin-top: 32rpx;
        margin-left: 0;
      }

      .area_input {
        position: relative;
        padding-bottom: 48rpx;

        .text_count {
          position: absolute;
          right: 32rpx;
          bottom: 0;
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }
    }
  }

  .finish {
    padding: 32rpx;
    margin: 24rpx 32rpx;
    background: #fff;
    border-radius: 16rpx;

    .finish_title {
      padding-bottom: 32rpx;
      font-size: 32rpx;
      font-weight: 700;
      color: #222;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .list {
      .item {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-top: 32rpx;

        .imgs {
          width: 40rpx;
          height: 40rpx;
        }

        .title {
          margin-left: 16rpx;
          font-size: 32rpx;
          font-weight: 500;
          color: #222;
        }

        .detail {
          width: 152rpx;
          height: 56rpx;
          margin-left: 48rpx;
          font-size: 26rpx;
          font-weight: 400;
          line-height: 56rpx;
          color: #a46b39;
          text-align: center;
          border: 1rpx solid #a46b39;
          border-radius: 38rpx;
        }
      }
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;

    .pre_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 700;
      color: #a46b39;
      background: #fff;
      border: 1rpx solid #a46b39;
      border-radius: 44rpx;
    }

    .next_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
      background: #a46b39;
      border-radius: 44rpx;
    }
  }

  ::v-deep .u-modal__title {
    font-size: 34rpx !important;
    font-weight: 700 !important;
    color: #222 !important;
  }
}
</style>
